import geopandas
import matplotlib.pyplot as plt
import sys
import json
import os


def visualize(sourceFilePath: str, pngFileName: str, boundingBoxFileName: str, columnName: str):
    # Load the geojson file
    geojson_geometry = geopandas.read_file(sourceFilePath)
    hu_dpi = 300
    fig, ax = plt.subplots(figsize=(10, 10))
    ax.set_axis_off()
    geojson_geometry = geojson_geometry.to_crs(crs='EPSG:4326')
    geojson_geometry.plot(ax=ax, column=columnName, scheme='quantiles', cmap='PuBu', legend=False)
    plt.savefig(pngFileName, dpi=hu_dpi, bbox_inches='tight', transparent=True)

    # Get the bounding box coordinates
    bbox = geojson_geometry.total_bounds
    lon_left, lat_bottom, lon_right, lat_top = bbox

    # Save the bounding box coordinates to a JSON file
    bounding_box_data = {
        "lon_left": lon_left,
        "lat_bottom": lat_bottom,
        "lon_right": lon_right,
        "lat_top": lat_top
    }

    with open(boundingBoxFileName, 'w') as f:
        json.dump(bounding_box_data, f, indent=4)

    # Print the bounding box coordinates
    print(f"Bounding box saved to {boundingBoxFileName}:")
    print(f"  lon_left={lon_left}")
    print(f"  lat_bottom={lat_bottom}")
    print(f"  lon_right={lon_right}")
    print(f"  lat_top={lat_top}")


if __name__ == '__main__':
    # Check if the required arguments are provided
    if len(sys.argv) < 5:
        print("Required parameters: sourceFilePath, pngFileName, boundingBoxFileName, columnName")
        sys.exit(1)

    # Read arguments from the command line
    source_geojson_file_path = sys.argv[1]  # e.g., source.geojson
    png_file_name = sys.argv[2]  # e.g., output.png
    bounding_box_file_name = sys.argv[3]  # e.g., bounding_box.json
    column_name_to_show = sys.argv[4]  # e.g., Ai

    # Call the visualize function with the provided arguments
    visualize(source_geojson_file_path, png_file_name, bounding_box_file_name, column_name_to_show)
